﻿using BySoft.Server.Business;
using BySoft.Server.Common;
using BySoft.Server.Common.Entity;
using BySoft.Server.Common.Enum;
using BySoft.Server.Consts;
using BySoft.Web.Utility;
using OneSoft.EntityCore;
using Org.BouncyCastle.Asn1.Ocsp;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BySoft.Web.Site.MasteData
{
    public partial class KnifeEdit : AuthBasePage
    {
        public string sequenceName
        {
            get { return "MD_Knife"; }
        }


        private string m_strTbl = "MD_Knife";
        private string m_strMainKey = "KnifeID";

        #region   read data 
        /// <summary>
        /// 绑定数据
        /// </summary>
        private void InitEditData()
        {
            string strCode = HttpUtility.UrlDecode(UIHelper.GetQueryStringValue("id").Trim());
            GetKnifeById(strCode);
            InitDtDUpFile();
           
        }

        private void GetKnifeById(string strCode)
        {
            if (!string.IsNullOrEmpty(strCode))
            {
                MdKnifeEntity Knife = MdKnife.GetMdKnifeByID(strCode);
                if (Knife != null)
                {
                    this.lblKnifeID.Text = Knife.KnifeID.Trim();
                    this.txtKnifeName.Text = Knife.KnifeName.Trim();
                    this.txtUnit.Text = Knife.Unit.Trim();
                    this.txtSpecifications.Text = Knife.Specifications.Trim();
                    this.txtSafeStock.Text = Knife.SafeStock.ToString();
                     this.txtBelongCustomer.Text = Knife.BelongCustomer.ToString();
                    this.txtFactory.Text = Knife.Factory.ToString();
                   
                    this.ddlKnifeType.SelectedValue = Knife.KnifeTypeID.Trim();
                    this.ddlKnifeStatus.SelectedValue = Knife.KnifeStatus;//刀具状态
            

                }



            }
        }

        //read map file
        private void InitDtDUpFile()
        {

            string KnifeID = HttpUtility.UrlDecode(UIHelper.GetQueryStringValue("id").Trim());
            if (!string.IsNullOrEmpty(KnifeID))
            {

                DataTable dTable = DtDUpFile.Copy();
                InitAttachmentFileDt(KnifeID, dTable, "KnifeMap");
                DtDUpFile = dTable.Copy();

                BindMapFileData();
            }
        }


        private  DataTable InitAttachmentFileDt(string KnifeID, DataTable dTable, string strFormType)
        {
            DataTable dt = MdAttachment.GetMdAttachment(KnifeID, strFormType);
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    DataRow d = dTable.NewRow();
                    d["AttachmentID"] = CommonMethod.GetString(dr["AttachmentID"]);
                    d["FileType"] = CommonMethod.GetString(dr["FileType"]);
                    d["FileSize"] = CommonMethod.GetString(dr["FileSize"]);
                    d["UpDateTime"] = CommonMethod.GetString(dr["UpDateTime"]);
                    d["FileURL"] = CommonMethod.GetString(dr["FileURL"]);
                    d["FileName"] = CommonMethod.GetString(dr["FileName"]);
                    d["FormType"] = CommonMethod.GetString(dr["FormType"]);
                    d["FormID"] = CommonMethod.GetString(dr["FormID"]);
                    d["Status"] = CommonMethod.GetString(dr["Status"]);
                    d["AttachmentID"] = CommonMethod.GetString(dr["AttachmentID"]);
                    string path = "/UpFile/";
                    path += strFormType + "/" + d["FileURL"];
                    path = Request.Url.Scheme + "://" + Request.Url.Authority + path;
                    d["OpenURL"] = path;
                    dTable.Rows.Add(d);
                }
            }
            return dt;
        }
        
        #endregion
     
       



        #region Attachment File

        /// <summary>
        /// 图纸文件的datatable     与upKnifeFile 统一
        /// </summary>
        protected DataTable DtDUpFile
        {
            get
            {
                if (Session[SessionMapName] != null)
                {
                    return (DataTable)Session[SessionMapName];
                }
                else
                {
                    return CreateUpFileDT();
                }
            }
            set
            {
                Session[SessionMapName] = value;
            }
        }

       

        private DataTable CreateUpFileDT()
        {
           

            return MdKnife.CreateUpFileDT();

        }
        #endregion



        static string SessionMapName = "";
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {


                BindDDLKnifeType();

                SessionMapName = MdKnife.QuerySessionFileName("7");
                

                Session[SessionMapName] = null;

              

                InitEditData();
               
              
            }
            Master.ValidationGroup = "gSubmit";
            UIHelper.RunScript(this.UpdatePanel1, "Refreashtab();iframeAutoFit();");
        }

        protected void btnAddMapFileHide_Click(object sender, EventArgs e)
        {
            try
            {
                BindMapFileData();
            }
            catch (Exception ex) { UIHelper.Alert(this.Page, FomatString(ex.Message.ToString())); }
        }

        private void BindMapFileData()
        {
            try
            {
                foreach (DataRow dr in DtDUpFile.Rows)
                {
                    dr["FormID"] = lblKnifeID.Text.Trim();
                }

                grdResultMap.DataSource = DtDUpFile;
                grdResultMap.DataBind();
                UIHelper.RunScript(this.Page, "iframeAutoFit(); ");
            }
            catch { }
        }



    

       

        private void ChangeKnifeID()
        {
            //by zhang
            this.lblKnifeID.Text = ClsComm.GetMaxSequenceID(sequenceName + ddlKnifeType.SelectedValue.Trim(), ddlKnifeType.SelectedValue.Trim(), 4);
        }

        private void BindDDLKnifeType()
        {
            DataTable dt = MdKnifetype.GetMdKnifetypeAll().Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                this.ddlKnifeType.DataSource = dt;
                this.ddlKnifeType.DataTextField = "KnifeTypeName";
                this.ddlKnifeType.DataValueField = "KnifeTypeID";
                this.ddlKnifeType.DataBind();
            }
            UIHelper.InsertFirstItem(ddlKnifeType);


            BindParameterForDDL("KnifeStatus", ddlKnifeStatus);
            UIHelper.InsertFirstItem(ddlKnifeStatus);
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                //GetGridViewData();
                if (string.IsNullOrEmpty(CurrentUser.UserID))
                {
                    UIHelper.AlertMessage(this.Page, "等待时间太久，请重新填写刀具资料！");
                    return;
                }
                if (!string.IsNullOrEmpty(this.lblKnifeID.Text.Trim()))
                {
                    if (!(ValidateData()))
                    {
                      
                        return;
                    }
                    MdKnifeEntity Knife = new MdKnifeEntity();
                    Knife.KnifeID = this.lblKnifeID.Text.Trim();
                    Knife.KnifeName = this.txtKnifeName.Text.Trim();
                    Knife.Unit = this.txtUnit.Text.Trim();
                    Knife.Specifications = this.txtSpecifications.Text.Trim();
                    Knife.KnifeTypeID = this.ddlKnifeType.SelectedValue.Trim();
                    Knife.SafeStock = GetDecimal(txtSafeStock);
                    Knife.Factory = GetString(txtFactory); ;
                    Knife.BelongCustomer = GetString(txtBelongCustomer);
                    Knife.Status = "1";
                    Knife.KnifeStatus = ddlKnifeStatus.SelectedValue;

                    Knife.ModifyDate = DateTime.Now;
                    Knife.ModifyUserID = CurrentUser.UserID;
                    Knife.ModifyUserName = CurrentUser.UserName;


                    List<MdAttachmentEntity> dtResultMapFile = GetDataViewFiles(Knife.KnifeID, DtDUpFile, "KnifeMap");
                

                    if (MdKnife.Save(Knife, dtResultMapFile, false))
                    {
                        ClsComm.SetMaxSequenceID(sequenceName + ddlKnifeType.SelectedValue.Trim());
                        base.LogAction(BaseEnum.ActionType.Add, Knife.KnifeID, true, null, new EntityBase[] { Knife });
                        UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "../MasteData/KnifeList.aspx");
                    }
                    else
                    {
                        UIHelper.AlertMessage(this.Page, Message.SaveFail);
                    }
                }

            }
            catch (Exception ex)
            {
                UIHelper.AlertMessage(this.Page, FomatString(ex.Message.ToString()));
            }
        }

        private static List<MdAttachmentEntity> GetDataViewFiles(string strKnifeID, DataTable dt, string strFormType)
        {
            List<MdAttachmentEntity> lstyFile = new List<MdAttachmentEntity>();
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow drItem in dt.Rows)
                {
                    MdAttachmentEntity Detailentity = new MdAttachmentEntity();
                    Detailentity.AttachmentID = Guid.NewGuid().ToString();
                    Detailentity.FileType = CommonMethod.GetString(drItem["FileType"]);
                    Detailentity.FileSize = Convert.ToInt32(drItem["FileSize"]);
                    Detailentity.UpDateTime = DateTime.Now;
                    Detailentity.FileURL = CommonMethod.GetString(drItem["FileURL"]);
                    Detailentity.FileName = CommonMethod.GetString(drItem["FileName"]);
                    Detailentity.FormType = strFormType;//"entity";
                    Detailentity.FormID = strKnifeID;
                    Detailentity.Status = "1";
                    lstyFile.Add(Detailentity);
                }
            }
            return lstyFile;

        }

        protected void ddlKnifeType_SelectedIndexChanged(object sender, EventArgs e)
        {
            ChangeKnifeID();
        }


        protected void btnAddhid_Click(object sender, EventArgs e)
        {
            try
            {
                BindMapFileData();

            }
            catch (Exception ex) { }

        }

        protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
                Button btnDel = (Button)e.Row.FindControl("btnDel");
                if (ibtn != null)
                {
                    ibtn.OnClientClick = "ShowTopConfirm('提示信息','" + Message.ConfirmDelete + "','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
                }
            }
        }


        protected void grdResultMap_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strCode = e.CommandArgument.ToString();
            string[] strs = strCode.Split(',');
            switch (e.CommandName)
            {
                case "del":

                    // GetGridViewData();
                    DataTable dtTemp = DtDUpFile.Copy();

                    DataRow[] drsSelect = dtTemp.Select("AttachmentID='" + strCode + "'");
                    if (drsSelect != null && drsSelect.Length > 0)
                    {
                        dtTemp.Rows.Remove(drsSelect[0]);
                        dtTemp.AcceptChanges();
                        DtDUpFile = dtTemp.Copy();
                        BindMapFileData();
                    }

                    UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);

                    break;

                default:
                    break;
            }
        }



       




        #region 数据有效验证
        private bool ValidateData()
        {
            string strMention = "";




            if (string.IsNullOrEmpty(ddlKnifeType.SelectedValue))
            {
                strMention += "请选择刀具类别！";
            }
            if (string.IsNullOrEmpty(txtKnifeName.Text.Trim()))
            {
                strMention += "请输入刀具名称！";
            }

            MdKnife entity = new MdKnife();
            //if (entity.IsIDExists(this.lblKnifeID.Text.Trim()))
            //{
            //    ChangeKnifeID();
            //    strMention += "刀具编号已存在，请重新保存！";

            //}

            if (entity.IsNameExists(this.txtKnifeName.Text.Trim(), this.lblKnifeID.Text.Trim()))
            {
                 strMention += "刀具名称已存在，请重新输入！";

            }

            if (string.IsNullOrEmpty(strMention))
            {
                return true;
            }
            else
            {
                UIHelper.AlertMessage(this.Page, strMention);
                return false;
            }
        }


        #endregion


     


    }
}